from flask import Flask, render_template, request, redirect, url_for, jsonify
import os
import json
from datetime import datetime
import markdown
from pathlib import Path

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key-here'

# 数据存储路径
DATA_DIR = Path('data')
POSTS_FILE = DATA_DIR / 'posts.json'
TAGS_FILE = DATA_DIR / 'tags.json'

# 确保数据目录存在
DATA_DIR.mkdir(exist_ok=True)

# 初始化数据文件
if not POSTS_FILE.exists():
    POSTS_FILE.write_text('[]', encoding='utf-8')
if not TAGS_FILE.exists():
    TAGS_FILE.write_text('[]', encoding='utf-8')

def load_posts():
    """加载所有文章"""
    try:
        with open(POSTS_FILE, 'r', encoding='utf-8') as f:
            posts = json.load(f)
            # 按时间倒序排序
            posts.sort(key=lambda x: x['created_at'], reverse=True)
            return posts
    except:
        return []

def save_posts(posts):
    """保存文章列表"""
    with open(POSTS_FILE, 'w', encoding='utf-8') as f:
        json.dump(posts, f, ensure_ascii=False, indent=2)

def load_tags():
    """加载所有标签"""
    try:
        with open(TAGS_FILE, 'r', encoding='utf-8') as f:
            return json.load(f)
    except:
        return []

def save_tags(tags):
    """保存标签列表"""
    with open(TAGS_FILE, 'w', encoding='utf-8') as f:
        json.dump(list(set(tags)), f, ensure_ascii=False, indent=2)

@app.route('/')
def index():
    """首页 - 文章列表"""
    posts = load_posts()
    tags = load_tags()
    selected_tag = request.args.get('tag', '')
    
    if selected_tag:
        posts = [p for p in posts if selected_tag in p.get('tags', [])]
    
    return render_template('index.html', posts=posts, tags=tags, selected_tag=selected_tag)

@app.route('/post/<int:post_id>')
def post_detail(post_id):
    """文章详情页"""
    posts = load_posts()
    post = next((p for p in posts if p['id'] == post_id), None)
    
    if not post:
        return "文章不存在", 404
    
    # 渲染Markdown内容
    md = markdown.Markdown(extensions=['codehilite', 'fenced_code'])
    post['content_html'] = md.convert(post['content'])
    
    return render_template('post_detail.html', post=post)

@app.route('/admin')
def admin():
    """管理后台"""
    posts = load_posts()
    return render_template('admin.html', posts=posts)

@app.route('/admin/new')
def new_post():
    """新建文章页面"""
    tags = load_tags()
    return render_template('edit_post.html', post=None, tags=tags)

@app.route('/admin/edit/<int:post_id>')
def edit_post(post_id):
    """编辑文章页面"""
    posts = load_posts()
    post = next((p for p in posts if p['id'] == post_id), None)
    
    if not post:
        return "文章不存在", 404
    
    tags = load_tags()
    return render_template('edit_post.html', post=post, tags=tags)

@app.route('/api/posts', methods=['POST'])
def save_post():
    """保存文章API"""
    data = request.json
    
    posts = load_posts()
    tags = load_tags()
    
    if 'id' in data and data['id']:
        # 更新现有文章
        for i, post in enumerate(posts):
            if post['id'] == data['id']:
                posts[i] = {
                    'id': data['id'],
                    'title': data['title'],
                    'content': data['content'],
                    'tags': data.get('tags', []),
                    'created_at': post['created_at'],
                    'updated_at': datetime.now().isoformat()
                }
                break
    else:
        # 新建文章
        new_id = max([p['id'] for p in posts], default=0) + 1
        new_post = {
            'id': new_id,
            'title': data['title'],
            'content': data['content'],
            'tags': data.get('tags', []),
            'created_at': datetime.now().isoformat(),
            'updated_at': datetime.now().isoformat()
        }
        posts.append(new_post)
    
    # 更新标签
    for tag in data.get('tags', []):
        if tag not in tags:
            tags.append(tag)
    
    save_posts(posts)
    save_tags(tags)
    
    return jsonify({'success': True})

@app.route('/api/posts/<int:post_id>', methods=['DELETE'])
def delete_post(post_id):
    """删除文章API"""
    posts = load_posts()
    posts = [p for p in posts if p['id'] != post_id]
    save_posts(posts)
    
    return jsonify({'success': True})

@app.route('/api/tags')
def get_tags():
    """获取所有标签API"""
    tags = load_tags()
    return jsonify(tags)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
